'''
Created on Feb 3, 2010

@author: alexey
'''
import subprocess,os,string
import shutil
from util import *


    
         


class HParse:
    
    def run(self):
        result = subprocess.Popen(["HParse", "config/gram","wdnet"], stdout=subprocess.PIPE).communicate()[0]
        log(result)

class HCopy:
    
    def run(self, folder_name,file_set, config_file ):
        labels_file = "%s%s" % (folder_name, ".mlf")
        mfc_file =  "%s%s" % (folder_name, ".mfc")
        file_list_file =  "%s%s" % (folder_name, ".scp")
        srcFolderContainer = 'audioSRC'
        srcFolder = os.getcwd()
        labelsFileContent = []
        for folder in file_set:
            entries = getFileList(srcFolder,srcFolderContainer, folder)
            labelsFileContent.extend(entries)
        
        fileContent = createLabelsMLF(labelsFileContent)
        wavFiles,mfcFiles,labelFiles = createFileList(labelsFileContent, folder_name) 
        fileListCon = prepareFileList(wavFiles,mfcFiles)
        createLabelFiles(labelFiles)
        writeToFile(labels_file, fileContent)
        writeToFile(file_list_file, fileListCon)
        writeToFile(mfc_file, mfcFiles)
        result = subprocess.Popen(["HCopy", "-C", config_file ,"-I",labels_file , "-S", file_list_file], stdout=subprocess.PIPE).communicate()[0]
        log(result)


class HCompV:
    def run(self,config_file, file_list ):
        hmm0FolderName = "hmm0"
        if  os.path.exists(hmm0FolderName): 
            shutil.rmtree(hmm0FolderName)
        os.makedirs(hmm0FolderName)
        result = subprocess.Popen(["HCompV", "-C",config_file,"-f","0.01","-m","-S",file_list,"-M","hmm0","config/proto"], stdout=subprocess.PIPE).communicate()[0]
        log(result)
        #prepare macros
        linesToAdd = []
        with open('hmm0/proto', 'r') as f:
            #read first 3 lines
            linesToAdd.append(f.readline())
            linesToAdd.append(f.readline())
            linesToAdd.append(f.readline())
        with open('hmm0/macros','w') as f:
            for line in linesToAdd:
                f.write(line)
            with open('hmm0/vFloors') as vFloors:
                for line in vFloors:
                    f.write(line)
        #prepare hmmdefs
        
        header = '~h "%s"\n'
        protoLines = []
        with open ('hmm0/proto','r') as proto:
            for line in proto:
                protoLines.append(line)
        #don't need to copy fist first 3 lines
        hmmInit = protoLines[4:]
        with open('hmm0/hmmdefs','w') as hmmdefs:
            for hmm in listOfHmms:
                hmmdefs.write(header % hmm)
                for line in hmmInit:
                    hmmdefs.write(line)
                
            


class HERest:
    
    def run(self ,config_file, labels_file,script_file,prev_folder,new_folder):
        if  os.path.exists(new_folder): 
            shutil.rmtree(new_folder)
        os.makedirs(new_folder)
        result = subprocess.Popen(["HERest", "-C",config_file,"-I", labels_file,"-t","250.0","150.","1000.0","-S",script_file,"-H","%s/macros" % prev_folder,"-H","%s/hmmdefs" % prev_folder,"-M",new_folder,"config/monophones0"], stdout=subprocess.PIPE).communicate()[0]
        log(result)
#HERest -C herest_config -I labels.mlf -t 250.0 150. 1000.0 -S train.scp -H hmm0/macros -H hmm0/hmmdefs -M hmm1 monophones0
#HERest -C herest_config -I labels.mlf -t 250.0 150. 1000.0 -S train.scp -H hmm1/macros -H hmm1/hmmdefs -M hmm2 monophones0
#HERest -C herest_config -I labels.mlf -t 250.0 150. 1000.0 -S train.scp -H hmm2/macros -H hmm2/hmmdefs -M hmm3 monophones0


class HVite:
    def run(self):
        result = subprocess.Popen(["HVite", "-m","-n","10","10","-H","hmm3/macros","-H","hmm3/hmmdefs","-S","test.mfc","-l","'*'","-i","recout.mlf","-w","wdnet","-s","5.0","config/dict","config/HmmList"], stdout=subprocess.PIPE).communicate()[0]
        log(result)
#HVite -H hmm3/macros -H hmm3/hmmdefs -S test.scp -l '*' -i recout.mlf -a -p 0.0 -s 5.0 dict HmmList

class HResults:
    def run(self):
        labelFileContent = []
        labelFileContent.append("#!MLF!#")
        for hmm in listOfHmms:
            labelFileContent.append('"\'*\'/%s.lab"' % hmm)
            labelFileContent.append(hmm)
            labelFileContent.append('.')
        writeToFile("labels.mlf",labelFileContent)
        result = subprocess.Popen(["HResults", "-p","-s","-I","labels.mlf","config/HmmList","recout.mlf"], stdout=subprocess.PIPE).communicate()[0]
        log(result)
# HResults -I testref.mlf HmmList recout.mlf

def deleteFolder(name):
    if  os.path.exists(name): 
        shutil.rmtree(name)
        
def deleteFile(name):
    path = os.path.join(os.getcwd(), name)
    if os.access(path, os.F_OK):    
        os.remove(path)
    else:
        log("File not found %s" % path)
###########################################################
#Available sets 'first','second','third','forth','fifth' 'sixth' 'seventh'
trainingSet = ['third','forth','fifth']
testingSet = [ 'second','first']
listOfHmms = ['one','two','three','four','five','six','seven','eight','nine','ten']

#clean up
deleteFolder('test')
deleteFolder('train')
deleteFolder('hmm0')
deleteFolder('hmm1')
deleteFolder('hmm2')
deleteFolder('hmm3')

deleteFile('train.scp')
deleteFile('train.mlf')
deleteFile('train.mfc')
deleteFile('test.scp')
deleteFile('test.mlf')
deleteFile('test.mfc')
deleteFile('recout.mlf')
deleteFile('labels.mlf')
deleteFile('wdnet')

exit()
hparse =HParse()
hparse.run()
hcopy = HCopy()
hcopy.run("train", trainingSet,"config/hcopy_config")
hcopy.run("test", testingSet,"config/hcopy_config")
hcompv = HCompV()
hcompv.run("config/hcompv_config", "train.mfc")
herest = HERest()
herest.run("config/herest_config", "train.mlf", "train.mfc", "hmm0", "hmm1")
herest.run("config/herest_config", "train.mlf", "train.mfc", "hmm1", "hmm2")
herest.run("config/herest_config", "train.mlf", "train.mfc", "hmm2", "hmm3")
hvite = HVite()
hvite.run()
hresults = HResults()
hresults.run()
